package cn.holy.app.xcddt.ui.activity.login

import androidx.lifecycle.Observer
import android.text.TextUtils
import cn.holy.app.xcddt.R
import cn.holy.app.xcddt.app.App
import cn.holy.app.xcddt.domain.UserBean
import cn.holy.app.xcddt.net.callback.LoadingCallback
import cn.holy.app.xcddt.ui.activity.base.BaseActivity
import cn.holy.app.xcddt.ui.activity.login.view.LoginViewModel
import com.alibaba.android.arouter.facade.Postcard
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.facade.callback.NavigationCallback
import com.alibaba.android.arouter.launcher.ARouter
import com.qmuiteam.qmui.util.QMUIKeyboardHelper
import com.qmuiteam.qmui.util.QMUIStatusBarHelper
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog
import kotlinx.android.synthetic.main.activity_login.*
import javax.inject.Inject


@Route(path = "/app/login")
class LoginActivity : BaseActivity() {


    @Inject
    lateinit var loginViewModel: LoginViewModel


    override fun initView() {
        App.appComponent.inject(this)
        QMUIStatusBarHelper.translucent(this)
        QMUIStatusBarHelper.setStatusBarLightMode(this)
    }

    override fun initData() {

        val loginFormBean = loginViewModel!!.loadLoginInfo()
        et_username.setText(loginFormBean.username)
        et_password.setText(loginFormBean.password)
        //

        if (App.sharedPreferences.getString("token", "") != "") {
            ARouter.getInstance().build("/app/main").navigation()
            finish()
        }
        btn_login.setOnClickListener {
            QMUIKeyboardHelper.hideKeyboard(et_password)
            if (TextUtils.isEmpty(et_username.text.toString())) {
                showTips("请输入账号", QMUITipDialog.Builder.ICON_TYPE_INFO)
                return@setOnClickListener
            }
            val loading = getLoading("正在登录")
            loginViewModel.login(et_username.text.toString(), et_password.text.toString(), cb_agree.isChecked, object : LoadingCallback<UserBean> {
                override fun onSuccess() {
                }

                override fun onStart() {
                    loading.show()
                }

                override fun onError(msg: String) {
                    hideLoading(loading);
                    showTips(msg, QMUITipDialog.Builder.ICON_TYPE_FAIL)
                }

                override fun onSuccess(user: UserBean) {
                    hideLoading(loading);
                    showTips("登录成功", QMUITipDialog.Builder.ICON_TYPE_SUCCESS, object : Callback {
                        override fun onSuccess() {
                            ARouter.getInstance().build("/app/main").navigation()
                            finish()
                        }
                    })
                }

                override fun onCompleted() {

                }
            })
        }
    }

    override fun initLayout() {
        setContentView(R.layout.activity_login)
    }

}
